package com.gltqe.cipher;


import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * 自定义 Jackson序列化器
 *
 * @author gltqe
 * @date 2023/6/14 15:03
 **/
public class CipherSerializer extends JsonSerializer<Object> {

    private static ObjectMapper mapper = new ObjectMapper();

    private CipherHandle cipherHandle;

    private Cipher cipher;

    public CipherSerializer(CipherHandle cipherHandle) {
        this.cipherHandle = cipherHandle;
    }

    /**
     * 序列化
     *
     * @author gltqe
     * @date 2023/6/15 16:20
     **/
    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (cipher != null && o != null) {
            // 加密
            String json = mapper.writeValueAsString(o);
            Object value = this.cipherHandle.encryptHandle(cipher, json);
            jsonGenerator.writeObject(value);
        }
    }


    /**
     * 设置加解密注解
     *
     * @param cipher
     * @author gltqe
     * @date 2023/6/15 15:58
     **/
    public void setCipher(Cipher cipher) {
        this.cipher = cipher;
    }

    /**
     * 获取加解密处理器
     *
     * @return: org.gltqe.cipher.CipherHandle
     * @author gltqe
     * @date 2023/6/16 9:31
     **/
    public CipherHandle getCipherHandle() {
        return cipherHandle;
    }

}
